package com.grom.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.dispacher.context.ContextHolder;
import com.grom.po.Store;
import com.grom.service.StoreService;
import com.grom.util.JsonUtil;
import com.grom.util.SecurityUtil;
import com.holder.log.ConsoleLog;

public class StoreAction {
	public void gotoList() {
		List<Store> allStores = StoreService.instance.getAllStore();
		ContextHolder.setRequestAttribute("allStores", allStores);
		for (Store store : allStores) {
			ConsoleLog.debug(JsonUtil.parseToJson(store));
		}
		ContextHolder.forward("/WEB-INF/jsp/store/update.jsp");
	}

	public void doSave() {
		Store store = (Store) ContextHolder.initFromTheRequest(Store.class);
		if (store.getID() == null || store.getID().trim().equals("")) {
			StoreService.instance.add(store);
		} else {
			StoreService.instance.update(store);
			;
		}
		ContextHolder.sendRedirect(ContextHolder.findInstance().getContextUri()
				+ "/StoreAction/gotoList.do");
	}

	public void getDetail() {
		String id = ContextHolder.findInstance().getRequest()
				.getParameter("itemid");
		Store store = StoreService.instance.getStoreById(id);
		String json = JsonUtil.parseToJson(store);
		HttpServletResponse response = ContextHolder.findInstance()
				.getResponse();
		try {
			PrintWriter out = response.getWriter();
			out.write("store=" + json);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void doDelete() {
		String id = ContextHolder.findInstance().getRequest()
				.getParameter("deleteId");
		System.out.println("| StoreAction | doDelete | id | " + id);
		Store store = StoreService.instance.getStoreById(id);
		if (!SecurityUtil.isUserHasRight(store.getUserId())) {
			ContextHolder.sendRedirect(ContextHolder.findInstance()
					.getContextUri() + "/StoreAction/gotoList.do");
			return;
		}
		store.setID(id);
		StoreService.instance.delete(store);
		ContextHolder.sendRedirect(ContextHolder.findInstance().getContextUri()
				+ "/StoreAction/gotoList.do");
	}

	public void conditionSelect() {
		String storeAddress_s = ContextHolder.findInstance().getRequest()
				.getParameter("storeAddress_s");
		String sql = "select * from store where storeaddress like '%" + storeAddress_s
				+ "%';";
		List<Store> allStores = StoreService.instance.conditionSelect(sql);
		ContextHolder.setRequestAttribute("allStores", allStores);
		ContextHolder.forward("/WEB-INF/jsp/store/update.jsp");
	}
}
